package com.security.user.interceptor;

import com.security.user.model.UserInfo;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author yanggld
 * @Date 2020/3/9-16:37
 */
@Component
public class AclInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
        System.out.println("**********访问控制");

        UserInfo userInfo = (UserInfo)request.getAttribute("user");
        if (userInfo != null) {
            String method = request.getMethod();
            if (!userInfo.hasPermission(method)) {
                response.setStatus(HttpStatus.FORBIDDEN.value());
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write("禁止访问!");
                response.getWriter().flush();
                return false;
            }
        }
        return super.preHandle(request, response, handler);
    }
}
